<template>
  <a-card>
    <template #title>
      <span style="font-size: 20px; margin-left: 5px"> {{ isEdit ? '修改禁入圈' : '新增禁入圈' }}</span>
    </template>
    <a-button class="btn_normal_color" slot="extra" icon="rollback" @click="back">返回</a-button>
    <div>
      <a-form-model ref="myForm" :rules="rules" :model="info">
        <a-col :xxl="24" :lg="24" :sm="24">
          <a-form-model-item label="规则名称" prop="name" :labelCol="{ span: 2 }" :wrapperCol="{ span: 5 }">
            <a-input v-model="info.name" class="input-style" />
          </a-form-model-item>
        </a-col>
        <a-col :xxl="24" :lg="24" :sm="24">
          <a-col :xxl="8" :lg="8" :sm="24">
            <a-form-model-item label="开始时分：" prop="starthm" :labelCol="{ span: 6}" :wrapperCol="{ span: 15 }">
              <a-time-picker format="HH:mm" value-format="HH:mm" v-model="info.starthm" :style="{ width: 'calc(80% - 12px)' }" />
            </a-form-model-item>
          </a-col>

          <a-col :xxl="8" :lg="8" :sm="24">
            <a-form-model-item label="截止时分：" prop="endhm" :labelCol="{ span: 6 }" :wrapperCol="{ span: 15 }">
              <a-time-picker format="HH:mm" value-format="HH:mm" v-model="info.endhm" :style="{ width: 'calc(80% - 12px)' }" />
            </a-form-model-item>
          </a-col>
        </a-col>

        <a-col :xxl="24" :lg="24" :sm="24">
          <a-form-model-item label="社矫对象" prop="pernames" :labelCol="{ span: 2 }" :wrapperCol="{ span: 5 }">
            <a-input v-model="info.pernames" addon-after="请选择" @click="chooseCorrectPerson" />
          </a-form-model-item>
        </a-col>

        <a-col :xxl="8" :lg="8" :sm="24">
          <a-form-model-item label="范围区域" :labelCol="{ span: 6 }" :wrapperCol="{ span: 15 }">
            <a-tree-select
              v-model="geopointIds"
              show-search
              tree-checkable
              tree-node-filter-prop="title"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              placeholder="请选择"
              multiple
              allow-clear
              :tree-data="treeData"
              showArrow
              :replaceFields="{ children: 'children', title: 'name', key: 'id', value: 'id' }"
            >
            </a-tree-select>
            <span class="count-label-style">已选</span><span class="count-number-style">{{ geopointIds.length }}</span
            ><span class="count-label-style">个</span>
          </a-form-model-item>
        </a-col>

        <a-col :xxl="16" :lg="16" :sm="24">
          <a-form-model-item
            label="最近新增"
            v-if="recentGeopoints && recentGeopoints.length > 0"
            class="recent_div"
            :labelCol="{ span: 2 }"
            :wrapperCol="{ span: 20 }"
          >
            <div class="block-div" v-for="geopoint in recentGeopoints" :key="geopoint.id">
              <div class="block-label">
                <span class="block-lable-font beyond_hiding">{{ geopoint.name }}</span>
              </div>
            </div>
          </a-form-model-item>
        </a-col>

        <a-divider />

        <a-col :xxl="24" :lg="24" :sm="24">
          <a-form-model-item>
            <div style="text-align: right; margin-right: 80px">
              <a-button class="btn_primary_color" type="primary" style="width: 125px; height: 40px" @click="finish">
                完成
              </a-button>
              <a-button class="btn_normal_color" style="margin-left: 30px; width: 125px; height: 40px" @click="cancel">
                取消
              </a-button>
            </div>
          </a-form-model-item>
        </a-col>
      </a-form-model>
      <!-- 选择社矫对象 -->
      <SelectCorrectPerson :visible="openModel" :rule-id="ruleId" @close="closePersonModel" @ok="completeSelection" />
    </div>
  </a-card>
</template>
<script>
import { St_enableList, St_enableValue } from '@/enumeration/St_enable'
import { saveRuleSetting, viewZoneinRule, existsRuleName } from '@/api/correction/crw_rule_zonein'
import moment from 'moment'
import storage from 'store'
import { APP_USER } from '@/store/mutation-types'
import { geopointList, getQueryTree } from '@/api/correction/crc_geopoint'
import { geopointRuleList } from '@/api/correction/crw_rule_geopoint'

export default {
  components: { SelectCorrectPerson: () => import('@/views/correction/warning/SelectCorrectPerson.vue') },
  computed: {
    St_enableList() {
      return St_enableList
    },
  },
  data() {
    return {
      info: {
        id: undefined,
        name: undefined,
        pernames: undefined,
        status: St_enableValue.YES,
        starthm: undefined,
        endhm: undefined,
        createuserid: undefined,
        createusername: undefined,
        createtime: undefined,
      },
      personIds: [],
      groupIds: [],
      openModel: false,
      rules: {
        name: [
          { required: true, message: '请输入规则名称', trigger: 'blur' },
          { min: 1, max: 33, message: '规则名称最大长度不能超过33', trigger: 'blur' }
        ],
        starthm: [
          { required: true, message: '请选择开始时分', trigger: 'change' }
        ],
        endhm: [
          { required: true, message: '请选择结束时分', trigger: 'change' }
        ]
      },
      geopoints: [],
      treeData: [],
      geopointIds: [],
      ruleId: undefined,
      recentGeopoints: [], // 最近范围的数据
      isEdit: false,
    }
  },
  methods: {
    async finish() {
      let validateFlag
      this.$refs.myForm.validate((valid) => {
        validateFlag = valid
      })
      if (!validateFlag) {
        this.$message.warning('请填写必填信息！')
        return
      }
      console.log(this.info)
      console.log(this.groupIds)

      if (!this.isEdit) {
        const existsResult = await existsRuleName(this.info.name)
        if (existsResult.code !== 0) {
          this.$message.error('校验规则名称是否存在失败!')
          return
        }
        if (existsResult.data) {
          this.$message.error('该规则名称已存在，请换个名称!')
          return
        }
      }

      const { code } = await saveRuleSetting(
        this.info,
        this.personIds.join(','),
        this.groupIds.join(','),
        this.geopointIds.join(',')
      )
      if (code !== 0) {
        this.$message.error('保存禁入圈设置失败!')
        return
      }
      this.$message.success('保存成功')
      this.back()
    },
    cancel() {
      this.back()
    },
    back() {
      this.$router.push({
        path: '/CorrectZoneIn',
        query: this.$route.query,
      })
    },
    chooseCorrectPerson() {
      this.openModel = true
    },
    closePersonModel() {
      this.openModel = false
    },
    completeSelection(checkedPersonIds, checkedGroupIds, pernames) {
      this.openModel = false
      this.personIds = checkedPersonIds
      this.groupIds = checkedGroupIds
      this.info.pernames = pernames
      console.log(checkedPersonIds, checkedGroupIds, pernames)
    },
    geopointChange(value) {
      this.geopointIds = value
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    setTreeNode(treeData) {
      if (treeData && treeData.length > 0) {
        treeData.forEach(item => {
          if (item.geopoints && item.geopoints != null) {
            item.disabled = false
          } else {
            item.disabled = true
          }
          if (item.children && item.children.length > 0) {
            this.setTreeNode(item.children)
          }
        })
      }
    },
    findRecentArea() {
      geopointList({ pageSize: 10, sort: 'createtime', order: 'desc', f_createtime: '1900-01-01' }).then((res) => {
        if (res.code !== 0) {
          console.log('查询最近新增范围失败')
        } else {
          this.geopoints = res.data.records
          this.recentGeopoints = this.geopoints
            .filter((el) => el.createtime != null)
            .sort((a, b) => {
              return b.createTime < a.createTime ? -1 : 1
            })
          // 获取前四个
          if (this.recentGeopoints) {
            if (this.recentGeopoints.length > 4) {
              this.recentGeopoints = this.recentGeopoints.splice(0, 4)
            }
          }
        }
      })
    },
  },
  async created() {
    this.ruleId = this.$route.query.ruleId
    this.treeData = []
    this.findRecentArea()
    const geopointResult = await getQueryTree()
    if (geopointResult.code !== 0) {
      this.$message.error('未获取到地图范围信息')
      return
    }
    this.treeData = geopointResult.data
    console.log('查询数据', this.treeData)
    this.setTreeNode(this.treeData)
    // 获取前四个
    if (this.recentGeopoints) {
      if (this.recentGeopoints.length > 4) {
        this.recentGeopoints = this.recentGeopoints.splice(0, 4)
      }
    }
    if (this.ruleId) {
      this.isEdit = true
      const { code, data } = await viewZoneinRule(this.ruleId)
      if (code !== 0) {
        this.$message.error('未获取到规则详细信息')
        return
      }
      this.info = data

      const geopointRuleResult = await geopointRuleList({ f_ruleid: this.ruleId, pageSize: 99999 })
      if (geopointRuleResult.code !== 0) {
        this.$message.error('未获取到规则相关范围区域信息')
        return
      }
      this.geopointIds = geopointRuleResult.data.records.map((item) => item.geoid)
    } else {
      this.isEdit = false
      const today = moment().format('YYYY-MM-DD HH:mm:ss')
      this.info.name = '禁入圈规则-' + today
      this.info.createuserid = storage.get(APP_USER).userId
      this.info.createusername = storage.get(APP_USER).fullname
      this.info.createtime = today
    }
  },
}
</script>
<style lang="less" scoped>
::v-deep .ant-form-item-label {
  margin-right: 15px;
}

::v-deep .ant-form-item-label > label {
  font-size: 18px;
  font-family: 'PingFang-SC-Heavy';
  font-weight: 800;
  color: #2c2c2c;
}

.recent_div {
  ::v-deep .ant-form-item-label > label {
    font-size: 18px;
    font-family: 'PingFang-SC-Heavy';
    font-weight: 100;
    color: #2c2c2c;
  }
}

.input-style {
  height: 44px;
  background: #ffffff;
  border: 1px solid #e9e9e9;
  border-radius: 2px;
  color: #999999;
  font-size: 16px;
  font-family: PingFang SC;
}
::v-deep .ant-select-selection--multiple {
  min-height: 44px;
  background: #ffffff;
  border: 1px solid #e9e9e9;
  border-radius: 2px;
}
::v-deep .ant-select-selection__placeholder {
  height: 44px;
  margin-top: -5px;
}
::v-deep .ant-select-arrow {
  margin-top: -5px;
  color: rgba(0, 0, 0, 0.25);
  font-size: 18px;
}

.block-div {
  display: inline-block;
}
.block-label {
  min-width: 180px;
  height: 38px;
  background: #f6f6f6;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0px 10px 0px 10px;
}
.block-lable-font {
  font-size: 16px;
  font-family: PingFang SC;
  font-weight: 500;
  color: #666666;
  padding: 0px 15px 0px 15px;
}

.count-label-style {
  color: #999999;
  font-size: 16px;
  font-family: PingFang SC;
  margin-left: 5px;
  margin-right: 5px;
}
.count-number-style {
  color: #1890ff;
  font-size: 16px;
  font-family: PingFang SC;
  margin-left: 5px;
  margin-right: 5px;
  font-weight: 600;
}
</style>
